package com.srp.aop;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import com.srp.anno.Limit;
import com.srp.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class LimitAop {
    @Autowired
    private HttpServletRequest request;
    /**
     * 不同的接口，不同的流量控制
     * map的key为 Limiter.key+token
     */
    private final Map<String, RateLimiter> limitMap = Maps.newConcurrentMap();

    @Around("@annotation(com.srp.anno.Limit)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        //拿limit的注解
        Limit limit = method.getAnnotation(Limit.class);
        String url = String.valueOf(request.getQueryString());
        if (limit != null) {
            //key作用：不同的接口，不同的流量控制
            String token = request.getHeader("token");
            String key=limit.key()+token+ url;;
            RateLimiter rateLimiter = null;
            //验证缓存是否有命中key
            if (!limitMap.containsKey(key)) {
                // 创建令牌桶
                rateLimiter = RateLimiter.create(limit.permitsPerSecond());
                limitMap.put(key, rateLimiter);
                log.info("新建了令牌桶={}，容量={}",key,limit.permitsPerSecond());
            }
            rateLimiter = limitMap.get(key);
            // 拿令牌
            boolean acquire = rateLimiter.tryAcquire(limit.acquirePermitsPerSecond());

            log.info("                  "+ acquire);
            // 拿不到命令，直接返回异常提示
            if (!acquire) {
                log.info("令牌桶={}，获取令牌失败",key);

                return R.error(limit.msg());
            }


        }
        return joinPoint.proceed();
    }


}